const logger = require('../utils/logger');

/**
 * MigrationEngine
 * 负责执行数据库 DDL 操作 (Create/Alter Table)
 */
class MigrationEngine {
    constructor(knex) {
        this.knex = knex;
    }

    /**
     * 创建新表
     * @param {string} tableName 表名
     * @param {Array} fields 字段定义列表 [{name, type, required, unique}]
     */
    async createTable(tableName, fields) {
        try {
            const exists = await this.knex.schema.hasTable(tableName);
            if (exists) {
                throw new Error(`Table ${tableName} already exists`);
            }

            await this.knex.schema.createTable(tableName, (table) => {
                // 默认主键
                table.increments('id').primary();

                // 标准字段
                table.timestamp('created_at').defaultTo(this.knex.fn.now());
                table.timestamp('updated_at').defaultTo(this.knex.fn.now());

                // 业务字段
                fields.forEach(field => {
                    this._addFieldToTable(table, field);
                });
            });

            logger.info(`[Migration] Table ${tableName} created successfully`);
            return true;
        } catch (error) {
            logger.error(`[Migration] Failed to create table ${tableName}: ${error.message}`);
            throw error;
        }
    }

    /**
     * 向现有表添加字段
     * @param {string} tableName 
     * @param {Object} field 
     */
    async addColumn(tableName, field) {
        try {
            const hasColumn = await this.knex.schema.hasColumn(tableName, field.name);
            if (hasColumn) {
                throw new Error(`Column ${field.name} already exists in ${tableName}`);
            }

            await this.knex.schema.table(tableName, (table) => {
                this._addFieldToTable(table, field);
            });

            logger.info(`[Migration] Column ${field.name} added to ${tableName}`);
            return true;
        } catch (error) {
            logger.error(`[Migration] Failed to add column ${field.name}: ${error.message}`);
            throw error;
        }
    }

    /**
     * 内部方法：根据类型映射字段
     */
    _addFieldToTable(table, field) {
        let col;

        switch (field.type.toLowerCase()) {
            case 'text':
            case 'string':
                col = table.string(field.name);
                break;
            case 'integer':
            case 'int':
                col = table.integer(field.name);
                break;
            case 'real':
            case 'float':
            case 'number':
                col = table.float(field.name);
                break;
            case 'boolean':
                col = table.boolean(field.name);
                break;
            case 'date':
            case 'datetime':
                col = table.dateTime(field.name);
                break;
            case 'json':
                col = table.json(field.name);
                break;
            default:
                col = table.string(field.name); // 默认为字符串
        }

        if (field.required) {
            col.notNullable();
        }

        if (field.unique) {
            col.unique();
        }

        // 如果有默认值
        if (field.defaultValue !== undefined && field.defaultValue !== null) {
            col.defaultTo(field.defaultValue);
        }
    }
}

module.exports = MigrationEngine;
